
require"SDK"

local KEY_ACCOUNT_NAME = "account"
local KEY_ACCOUNT_PSW = "psw"
local KEY_LAST_SELECT_SERVER = 'LastSelectServer'
UILogin = {}

UILogin.uiRoot = nil
UILogin.uiEnter= nil
UILogin.uiSrv  = nil
	UILogin.uiSrvIcon = nil
	UILogin.uiSrvName = nil
	UILogin.uiSrvShow = nil
UILogin.uiName = nil
UILogin.uiBack = nil
UILogin.uiQQ   = nil
UILogin.uiWX   = nil
UILogin.uiAnim = nil

UILogin.http          = nil
UILogin.params        = nil
UILogin.isActivated   = nil
UILogin.activationCode= nil
UILogin.token         = nil
UILogin.serverSuggest = nil
UILogin.serverHistory = nil--{}--BM
UILogin.serverListAll = nil--{}--BM
UILogin.serverCurrent = nil

local function cleanSplashAnim()
	if not tolua.isnull(UILogin.uiAnim) then
		ccs.ArmatureDataManager:getInstance():removeArmatureFileInfo("ani/splash/fm_anim.ExportJson")
		ccs.ArmatureDataManager:getInstance():removeArmatureData(UILogin.uiAnim:getAnimation():getCurrentMovementID())
		UILogin.uiAnim:removeFromParent()
		UILogin.uiAnim = nil
	end
end

local function playSplashAnim()
	local uiRoot = UILogin.uiRoot
	ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("ani/splash/fm_anim.ExportJson")
	UILogin.uiAnim = ccs.Armature:create("fm_anim")
	UILogin.uiAnim:getAnimation():playWithIndex(0)
	UILogin.uiAnim:setPosition(uiRoot:getContentSize().width / 2, uiRoot:getContentSize().height / 2)
	uiRoot:addChild(UILogin.uiAnim)
end

local function showActivationInput()
	UIManager.pushScene("ui_activation",true)
end

function UILogin.setCurrentServerItem(serverItem)
	if nil ~= serverItem then 
		--UIManager.showToast("您选择了服务器 "..serverItem.name)--bm_test
		UILogin.serverCurrent = serverItem
		UILogin.uiSrvName:setString(serverItem.name)
		--bm 本地存档
		cc.UserDefault:getInstance():setStringForKey(KEY_LAST_SELECT_SERVER, serverItem.name)
	end
end

function UILogin.onLoginOurServer()
	UIManager.hideLoading()
	if UILogin.http and UILogin.http.status == 200 then
		local ret = json.decode(UILogin.http.response)
		if ret.result == 0 then
			ret.servers_history   = ret.servers_history or {}
			UILogin.isActivated   = true
			UILogin.token         = ret.security_code
			UILogin.serverSuggest = ret.servers_suggest
			UILogin.serverHistory = ret.servers_history
			UILogin.serverListAll = ret.servers_all
			
			local lastLoginServer = cc.UserDefault:getInstance():getStringForKey(KEY_LAST_SELECT_SERVER)
			local isMatch = false
			if nil ~= lastLoginServer then
				--UIManager.showToast("匹配服务器历史 "..lastLoginServer)--bm_test
				for i = #UILogin.serverListAll,1,-1 do
					if lastLoginServer ==  UILogin.serverListAll[i].name then 
						UILogin.setCurrentServerItem(UILogin.serverListAll[i])
						isMatch = true
					end
				end
			end
			
			if false == isMatch then 
				UILogin.setCurrentServerItem(UILogin.serverListAll[0])
			end
			
			--if #ret.servers_history > 0 then
			--	UILogin.setCurrentServerItem(ret.servers_history[1])
			--else
			--	UILogin.setCurrentServerItem(ret.servers_suggest[1])
			--end
			
			UILogin.uiSrv:setVisible(true)
			UILogin.uiEnter:setTitleText("进入游戏")
			if SDK.getChannel() == "qq" then
				UILogin.uiEnter:setVisible( true )
				UILogin.uiQQ:setVisible( false )
				UILogin.uiWX:setVisible( false )
			end
			SDK.saveNotifyUri(ret.notifyUri)--保存支付回调地址
			SDK.saveId(ret.user_id)
			if SDK.getChannel() == "kupai" then --kupai渠道保存accessToken和openId
				SDK.saveTokenAndId(ret.customData)
			end
            local info = { "v1" , ret.user_id , ret.username }
            SDK.doUserTD( info )
		elseif ret.result == 1 then
			UILogin.isActivated = false
			utils.PromptDialog(nil,ret.message and ret.message or "授权验证失败，请重新登录！")
			UILogin.params = nil
		elseif ret.result == 2 then
			UILogin.isActivated = false
			showActivationInput()
			utils.PromptDialog(nil,ret.message and ret.message or "激活码无效！")
		elseif ret.result == 3 then
			UILogin.isActivated = false
			showActivationInput()
			--utils.PromptDialog(nil,ret.message and ret.message or "需要激活码！")
		elseif ret.result == 4 then
			UILogin.isActivated = false
			utils.PromptDialog(nil,ret.message and ret.message or "账号不在白名单内！")
		end
	end
	UILogin.http = nil
end

function UILogin.doLoginOurServer()
	UIManager.showLoading()
	UILogin.http = cc.XMLHttpRequest:new()
	UILogin.http.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
	local url = nil
	--if SDK.getChannel() == "dev" then 
		-- UILogin.http = cc.XMLHttpRequest:new()
		cclog("--------------------=====dp.Logout()=======------------------")
		cclog("-----------------Request serverlist---------------------")
		-- url = "http://test2.293wan.com/serverlist.php?token="..dp.SERVER_LIST_KEY
		url = "http://123.207.20.230/serverlist.php?token="..dp.SERVER_LIST_KEY
		cclog("================================== request serverlist url = "..url)
	--[[[
	else
		
		url = dp.LOGIN_URL .. "?" .. UILogin.params  .. "&product_id=" .. tostring(cc.JNIUtils:getProductId())
		local di = SDK.getDeviceInfo()
		
		url = url .. "&channel_sub=" .. di.packageName .. "&code_version=" .. dp.PROGRAM_VER
		if UILogin.activationCode then
			url = url .. "&active_code=" .. UILogin.activationCode
		end
		
	end
	--]]
	UILogin.http:open("GET",url)
	UILogin.http:registerScriptHandler(UILogin.onLoginOurServer)
	UILogin.http:send()
end

local function onLogin(string)
	--BM
	--if device.platform == "windows" 
	--	or SDK.getChannel() == "dev" 
	--	then
		local userName = string
		--dp.SERVERS_IP = 
		--dp.SERVERS_PORT=
		dp.serverId   = 0
		dp.serverName = "开发"
		net.connect(dp.SERVERS_IP, dp.SERVERS_PORT, userName,nil)
	--[[
	else
		if #string > 0 then
			UILogin.params = string
			UILogin.isActivated = false
			UILogin.activationCode = nil
			UILogin.token = nil
			UILogin.uiBack:setVisible(true)
			UILogin.doLoginOurServer()
		else
			UIManager.showToast("渠道登录失败！")
		end

	end
	--]]
end

--BM
local combin = "#"

function UILogin.Show_LoginAccount()
	UILogin.uiSrvShow:setVisible(false)
	UILogin.uiSrvName:setVisible(false)

	UILogin.uiBack:setVisible(true)
	
	UILogin.uiEnter:setPressedActionEnabled(true)
	UILogin.uiEnter:addTouchEventListener(
		function(sender, eventType)
			if eventType == ccui.TouchEventType.ended then
				local name = UILogin.uiName:getText()
				local psw = UILogin.uiPassword:getText()	
				if #name > 0 then
					local out_string = string.match(name,'[%a%d]+') 
					if name == out_string then
						--SDK.doLogin(name,onLogin)
						if #psw > 0 then
							--UIManager.showToast("触发了 UILogin.Show_LoginAccount:login "..name.. psw)
							cc.UserDefault:getInstance():setStringForKey(KEY_ACCOUNT_NAME, name)
							cc.UserDefault:getInstance():setStringForKey(KEY_ACCOUNT_PSW, psw)
							SDK.doLogin(name..combin..psw,onLogin)
						else
							UIManager.showToast("请输入密码！")
						end
					else
						UIManager.showToast("用户名只能为英文或者数字！")
					end
				else
					UIManager.showToast("请输入用户名！")
				end
			end
		end
	)

	
	local x , y = UILogin.uiSrv:getPosition()
	--
	if nil == UILogin.uiName then
		UILogin.uiName = cc.EditBox:create(UILogin.uiSrv:getContentSize(), cc.Scale9Sprite:create("ui/fm_xuanqu_tiao01.png"))
		UILogin.uiName:setPosition(x,y+120)
		UILogin.uiName:setPlaceHolder("账号-登录自动注册")
		UILogin.uiName:setMaxLength(10)
		UILogin.uiRoot:addChild(UILogin.uiName,1)
		
		local old_name = cc.UserDefault:getInstance():getStringForKey(KEY_ACCOUNT_NAME)
		if #old_name > 0 then
			--UIManager.showToast("触发了 UILogin.Show_LoginAccount 的 SetName "..old_name)
			UILogin.uiName:setText(old_name)
		end
	else
		UILogin.uiName:setVisible(true)
	end
	
	--
	if nil == UILogin.uiPassword then
		UILogin.uiPassword = cc.EditBox:create(UILogin.uiSrv:getContentSize(), cc.Scale9Sprite:create("ui/fm_xuanqu_tiao01.png"))
		UILogin.uiPassword:setPosition(x,y)
		UILogin.uiPassword:setPlaceHolder("密码-登录自动注册")
		UILogin.uiPassword:setMaxLength(10)
		UILogin.uiRoot:addChild(UILogin.uiPassword,1)
		
		local old_psw = cc.UserDefault:getInstance():getStringForKey(KEY_ACCOUNT_PSW)
		if #old_psw >0 then 
			--UIManager.showToast("触发了 UILogin.Show_LoginAccount 的 set psw "..old_psw)
			UILogin.uiPassword:setText(old_psw)
		end
	else
		UILogin.uiPassword:setVisible(true)
	end
end

function UILogin.init()
	UILogin.uiRoot = ccui.Helper:seekNodeByName(UILogin.Widget, "image_basemap")
	UILogin.uiEnter= ccui.Helper:seekNodeByName(UILogin.Widget, "btn_enter")
	UILogin.uiSrv  = ccui.Helper:seekNodeByName(UILogin.Widget, "image_base_name")
	UILogin.uiSrvIcon = ccui.Helper:seekNodeByName(UILogin.Widget, "image_way")
	UILogin.uiSrvName = ccui.Helper:seekNodeByName(UILogin.Widget, "text_area")
	UILogin.uiSrvShow = ccui.Helper:seekNodeByName(UILogin.Widget, "text_choose")
	UILogin.uiBack = ccui.Helper:seekNodeByName(UILogin.Widget, "btn_back")
	UILogin.uiQQ   = ccui.Helper:seekNodeByName(UILogin.Widget, "btn_qq")
	UILogin.uiWX   = ccui.Helper:seekNodeByName(UILogin.Widget, "btn_weixin")
	
	--bm test
	--UIManager.pushScene("ui_login_choose")
	--[[
	if device.platform == "windows" or SDK.getChannel() == "dev" then
		UILogin.uiEnter:setPressedActionEnabled(true)
		UILogin.uiEnter:addTouchEventListener(
			function(sender, eventType)
				if eventType == ccui.TouchEventType.ended then
					local name = UILogin.uiName:getText()
					local psw = UILogin.uiPassword:getText()			
					if #name > 0 then
						local out_string = string.match(name,'[%a%d]+') 
						if name == out_string then
							--SDK.doLogin(name,onLogin)
							if #psw > 0 then
								SDK.doLogin(name..combin..psw,onLogin)
							else
								UIManager.showToast("请输入密码！")
							end
						else
							UIManager.showToast("用户名只能为英文或者数字！")
						end
					else
						UIManager.showToast("请输入用户名！")
					end
				end
			end
		)
		--
		local x , y = UILogin.uiSrv:getPosition()
		UILogin.uiName = cc.EditBox:create(UILogin.uiSrv:getContentSize(), cc.Scale9Sprite:create("ui/fm_xuanqu_tiao01.png"))
		UILogin.uiName:setPosition(x,y+120)
		UILogin.uiName:setPlaceHolder("请输入用户名")
		UILogin.uiName:setMaxLength(10)
		UILogin.uiRoot:addChild(UILogin.uiName,1)
		--
		UILogin.uiPassword = cc.EditBox:create(UILogin.uiSrv:getContentSize(), cc.Scale9Sprite:create("ui/fm_xuanqu_tiao01.png"))
		UILogin.uiPassword:setPosition(x,y)
		UILogin.uiPassword:setPlaceHolder("请输入密码")
		UILogin.uiPassword:setMaxLength(10)
		UILogin.uiRoot:addChild(UILogin.uiPassword,1)
		
		--		
		UILogin.uiSrv:removeFromParent()
		UILogin.uiSrv = nil
	else
	--]]
		local function onButtonEvent(sender, eventType)
			if eventType == ccui.TouchEventType.ended then
				if SDK.getChannel()=="qq" then
					if sender == UILogin.uiQQ then
						if not UILogin.params then
							SDK.doLogin("1",onLogin)
						elseif not UILogin.isActivated then --todo or not token
							UILogin.doLoginOurServer()
						elseif UILogin.serverCurrent.state == 0 then
							UIManager.showToast("服务器维护中，请稍候再试！")
						else
							dp.SERVERS_IP = UILogin.serverCurrent.ip
							dp.SERVERS_PORT=UILogin.serverCurrent.port
							dp.serverId   = UILogin.serverCurrent.id
							dp.serverName = UILogin.serverCurrent.name
							net.connect(dp.SERVERS_IP, dp.SERVERS_PORT,nil,UILogin.token)
						end
						return
					elseif sender == UILogin.uiWX then
						if not UILogin.params then
							SDK.doLogin("2",onLogin)
						elseif not UILogin.isActivated then --todo or not token
							UILogin.doLoginOurServer()
						elseif UILogin.serverCurrent.state == 0 then
							UIManager.showToast("服务器维护中，请稍候再试！")
						else
							dp.SERVERS_IP = UILogin.serverCurrent.ip
							dp.SERVERS_PORT=UILogin.serverCurrent.port
							dp.serverId   = UILogin.serverCurrent.id
							dp.serverName = UILogin.serverCurrent.name
							net.connect(dp.SERVERS_IP, dp.SERVERS_PORT,nil,UILogin.token)
						end
						return
					end
				end
				if sender == UILogin.uiEnter then
					if not UILogin.params then
						dp.SERVERS_IP = UILogin.serverCurrent.ip
						dp.SERVERS_PORT=UILogin.serverCurrent.port
						dp.serverId   = UILogin.serverCurrent.id
						dp.serverName = UILogin.serverCurrent.name
						UILogin.Show_LoginAccount()--SDK.doLogin("params",onLogin)
					elseif not UILogin.isActivated then --todo or not token
						UILogin.doLoginOurServer()
					elseif UILogin.serverCurrent.state == 0 then
						UIManager.showToast("服务器维护中，请稍候再试！")
					else
						dp.SERVERS_IP = UILogin.serverCurrent.ip
						dp.SERVERS_PORT=UILogin.serverCurrent.port
						dp.serverId   = UILogin.serverCurrent.id
						dp.serverName = UILogin.serverCurrent.name
						net.connect(dp.SERVERS_IP, dp.SERVERS_PORT,nil,UILogin.token)
					end
				elseif sender == UILogin.uiSrvShow then
					UIManager.pushScene("ui_login_choose")
				elseif sender == UILogin.uiBack then
					--UIManager.showToast("触发了 UILogin.init 的 onButtonEvent ")--bm_test
					SDK.doLogout("") --todo 是否需要回调
					UILogin.params = nil
					UILogin.uiSrv:setVisible(false)
					UILogin.uiEnter:setTitleText("登录")
					if SDK.getChannel() == "qq" then
						UILogin.uiEnter:setVisible( false )
						UILogin.uiQQ:setVisible( true )
						UILogin.uiWX:setVisible( true )
					end
					UILogin.uiBack:setVisible(false)
				end
			end
		end
		UILogin.uiSrvShow:addTouchEventListener(onButtonEvent)
		
		local function BackToSelectServer(sender, eventType)
			--UIManager.showToast("触发了 UILogin.Show_LoginAccount 的 BackToSelectServer ")--bm_test
			UILogin.uiSrvShow:setVisible(true)
			UILogin.uiSrvName:setVisible(true)
			
			UILogin.uiName:setVisible(false)
			UILogin.uiPassword:setVisible(false)
			
			UILogin.init()
		end
		UILogin.uiBack:setVisible(false)
		UILogin.uiBack:addTouchEventListener(BackToSelectServer)
		--UILogin.uiBack:addTouchEventListener(onButtonEvent)
		
		UILogin.uiEnter:addTouchEventListener(onButtonEvent)
		UILogin.uiEnter:setPressedActionEnabled(true)
        if SDK.getChannel()=="uc" then
            SDK.doLogin("params",onLogin)
        end
		if SDK.getChannel()=="qq" then
			UILogin.uiEnter:setVisible( false )
			UILogin.uiQQ:addTouchEventListener(onButtonEvent)
			UILogin.uiWX:addTouchEventListener(onButtonEvent)
		end
	--end
	print("---------------ui_login begin loginourserver-------------------")
	UILogin.doLoginOurServer()
	print("---------------ui_login end loginourserver-------------------")
end

function UILogin.setup()
	playSplashAnim()
	if device.platform == "windows" or SDK.getChannel() == "dev" then
		local old_name = cc.UserDefault:getInstance():getStringForKey(KEY_ACCOUNT_NAME)
		if #old_name > 0 and nil ~= UILogin.uiName then --BM
			UILogin.uiName:setText(old_name)
		end
	else
		UILogin.params = nil
		UILogin.uiSrv:setVisible(false)
		UILogin.uiEnter:setTitleText("登录")
		UILogin.uiBack:setVisible(false)
		if SDK.getChannel() =="qq" then
			UILogin.uiEnter:setVisible( false )
			UILogin.uiQQ:setVisible( true )
			UILogin.uiWX:setVisible( true )
		end
	end
	AudioEngine.playMusic("sound/login.mp3", true)
end

function UILogin.free()
	cleanSplashAnim()
	UILogin.params = nil
	UILogin.isActivated   = nil
	UILogin.token         = nil
	UILogin.activationCode= nil
	UILogin.serverSuggest = nil
	UILogin.serverHistory = nil
	UILogin.serverListAll = nil
	UILogin.serverCurrent = nil
end